package com.app.backend.common.serviceImpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.app.backend.common.dao.LogDao;
import com.app.backend.common.service.LogService;
import com.app.backend.common.base.BaseDao;
import com.app.backend.common.entity.Log;
import com.app.backend.common.vo.LogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: LogServiceImpl
 * @description:
 * @author: Zhun.Xiao
 * @create: 2020-02-09 22:16
 **/


@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class LogServiceImpl implements LogService {

    @Autowired
    LogDao logDao;

    @Override
    public BaseDao<Log, String> getRepository() {
        return logDao;
    }


    @Override
    public Page<Log> findByConditionPage(LogVo logVo, Pageable pageable) {

        return logDao.findAll(new Specification<Log>() {
            @Override
            public Predicate toPredicate(Root<Log> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Path<String> username = root.get("username");
                Path<String> ip = root.get("ip");
                Path<String> name = root.get("name");
                Path<Date> createTime = root.get("createTime");
                Set<Predicate> set = new HashSet<>();

                Predicate p1 = null, p2 = null, p3 = null;
                if (StrUtil.isNotEmpty(name.toString())) p1 = cb.like(name, '%' + logVo.getName() + '%');
                if (StrUtil.isNotEmpty(username.toString())) p2 = cb.like(username, '%' + logVo.getUsername() + '%');
                if (StrUtil.isNotEmpty(ip.toString())) p3 = cb.like(username, '%' + logVo.getIp() + '%');
                set.add(cb.or(p1, p2, p3));
                set.remove(null);
                if (StrUtil.isNotEmpty(logVo.getStartTime()) && StrUtil.isNotEmpty(logVo.getEndTime())) {
                    Date startTime = DateUtil.parse(logVo.getStartTime());
                    Date endTime = DateUtil.parse(logVo.getEndTime());
                    set.add(cb.between(createTime, startTime, DateUtil.endOfSecond(endTime)));
                }
                cq.where(set.toArray(new Predicate[set.size()]));
                return null;
            }
        }, pageable);

    }

}